import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { fakeAccountLogin, fakeAccountLogout, getFakeCaptcha } from '@/services/api';
import { setAuthority } from '@/utils/authority';
import { getPageQuery, isFakeData } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    isShowCaptcha: false,
  },

  effects: {
    *login({ payload }, { call, put }) {
      console.log('登录事件跟踪-step:002');
      const response = yield call(fakeAccountLogin, payload.values);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully  mall 请根据不同项目进行修改，替换为对应的前缀
      const lastLoginUser = `mall_last_username`;
      if (response.code === 0 || response.status === 'ok') {
        reloadAuthorized();

        // 如果当前登录人，刚刚登录过，咋这里跳回他上次 访问的目录，否则 跳回首页。
        if (localStorage.getItem(lastLoginUser) === payload.values.username) {
          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          let { redirect } = params;
          if (redirect) {
            const redirectUrlParams = new URL(redirect);
            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);
              if (redirect.match(/^\/.*#/)) {
                redirect = redirect.substr(redirect.indexOf('#') + 1);
              }
            } else {
              window.location.href = redirect;
              return;
            }
          }
          yield put(routerRedux.replace(redirect || '/'));
        } else {
          localStorage.setItem(lastLoginUser, payload.values.username);
          yield put(
            routerRedux.push({
              pathname: '/',
            })
          );
        }
      } else if (response.code === 900001) {
        payload.parentMethod.onGetImgCaptcha(); //自动刷新验证码
      } else if (payload.parentMethod.props.login.isShowCaptcha) {
        payload.parentMethod.onGetImgCaptcha(); //自动刷新验证码
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    //type: 'login/logout',
    *logout(_, { put, call }) {
      yield call(fakeAccountLogout);
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      //这里加一个判断，防止多次把系统打到登录页面
      //if (window.location.href.indexOf('/user/login') === -1) {
      let url = window.location.href;
      //这里replace 修改 有 publicPath， 访问不了的问题
      url = url.replace('/#/book/', '/#/');
      url = url.replace('/book/', '/');
      url = url.replace('/book/', '/');
      url = url.replace('/book/', '/');
      url = url.replace('/book/', '/');
      url = url.replace('%3Abook%3A', '/');
      yield put(
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
            redirect: url,
          }),
        })
      );
      //}
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      console.log('登录事件跟踪-step:003');
      setAuthority(payload.currentAuthority || 'admin');

      if (payload.status === false) {
        //退出
        state.isShowCaptcha = false;
      } else {
        //登录
        if (payload.code === 900001) {
          //弹出验证码
          state.isShowCaptcha = true;
        }
      }

      /* eslint-disable no-debugger */
      /* eslint-disable no-else-return */
      if (isFakeData()) {
        return {
          ...state,
          status: payload.status,
          type: payload.type,
        };
      } else {
        return {
          ...state,
          code: payload.code,
          msg: payload.msg,
          status: payload.status,
          type: payload.type,
        };
      }
    },
  },
};
